<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="yaf,rewrite,">










<meta name="description" content="Yar (Yet Another RPC Framework) 一个rpc框架Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.">
<meta name="keywords" content="yaf,rewrite">
<meta property="og:type" content="article">
<meta property="og:title" content="Yaf Yar使用">
<meta property="og:url" content="http://changyuan.github.io/2020/05/10/yaf/index.html">
<meta property="og:site_name" content="Chang Crazy&#39;s Blog">
<meta property="og:description" content="Yar (Yet Another RPC Framework) 一个rpc框架Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-05-10T06:51:38.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Yaf Yar使用">
<meta name="twitter:description" content="Yar (Yet Another RPC Framework) 一个rpc框架Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://changyuan.github.io/2020/05/10/yaf/">





  <title>Yaf Yar使用 | Chang Crazy's Blog</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Chang Crazy's Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">升级自己的操作系统</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-schedule">
          <a href="/schedule/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-calendar"></i> <br>
            
            日程表
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://changyuan.github.io/2020/05/10/yaf/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="changyuan">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Chang Crazy's Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Yaf Yar使用</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-05-10T14:51:38+08:00">
                2020-05-10
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Yar-Yet-Another-RPC-Framework-一个rpc框架"><a href="#Yar-Yet-Another-RPC-Framework-一个rpc框架" class="headerlink" title="Yar (Yet Another RPC Framework) 一个rpc框架"></a>Yar (Yet Another RPC Framework) 一个rpc框架</h1><p>Yar 是一个轻量级, 高效的RPC框架, 它提供了一种简单方法来让PHP项目之间可以互相远程调用对方的本地方法. 并且Yar也提供了并行调用的能力. 可以支持同时调用多个远程服务的方法.</p>
<a id="more"></a>
<h3 id="范例"><a href="#范例" class="headerlink" title="范例"></a>范例</h3><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//服务端</span></span><br><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 假设这个页面的访问路径是: http://example.com/operator.php */</span></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Operator</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Add two operands</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> interge </span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> interge</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">add</span><span class="params">($a, $b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">$this</span>-&gt;_add($a, $b);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Sub </span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">sub</span><span class="params">($a, $b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $a - $b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Mul</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function"><span class="keyword">function</span> <span class="title">mul</span><span class="params">($a, $b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $a * $b;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * Protected methods will not be exposed</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> interge </span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span> interge</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">protected</span> <span class="function"><span class="keyword">function</span> <span class="title">_add</span><span class="params">($a, $b)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> $a + $b;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$server = <span class="keyword">new</span> Yar_Server(<span class="keyword">new</span> Operator());</span><br><span class="line">$server-&gt;handle();</span><br><span class="line"><span class="meta">?&gt;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// 客户端</span></span><br><span class="line"></span><br><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line">$client = <span class="keyword">new</span> yar_client(<span class="string">"http://example.com/operator.php"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* call directly */</span></span><br><span class="line">var_dump($client-&gt;add(<span class="number">1</span>, <span class="number">2</span>));</span><br><span class="line"></span><br><span class="line"><span class="comment">/* call via call */</span></span><br><span class="line">var_dump($client-&gt;call(<span class="string">"add"</span>, <span class="keyword">array</span>(<span class="number">3</span>, <span class="number">2</span>)));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">/* __add can not be called */</span></span><br><span class="line">var_dump($client-&gt;_add(<span class="number">1</span>, <span class="number">2</span>));</span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="多个客户端异步调用"><a href="#多个客户端异步调用" class="headerlink" title="多个客户端异步调用"></a>多个客户端异步调用</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callback</span><span class="params">($ret, $callinfo)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">echo</span> $callinfo[<span class="string">'method'</span>] , <span class="string">" result: "</span>, $ret , <span class="string">"\n"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 注册一个异步调用 */</span></span><br><span class="line">Yar_Concurrent_Client::call(<span class="string">"http://example.com/operator.php"</span>, <span class="string">"add"</span>, <span class="keyword">array</span>(<span class="number">1</span>, <span class="number">2</span>), <span class="string">"callback"</span>);</span><br><span class="line">Yar_Concurrent_Client::call(<span class="string">"http://example.com/operator.php"</span>, <span class="string">"sub"</span>, <span class="keyword">array</span>(<span class="number">2</span>, <span class="number">1</span>), <span class="string">"callback"</span>);</span><br><span class="line">Yar_Concurrent_Client::call(<span class="string">"http://example.com/operator.php"</span>, <span class="string">"mul"</span>, <span class="keyword">array</span>(<span class="number">2</span>, <span class="number">2</span>), <span class="string">"callback"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */</span></span><br><span class="line">Yar_Concurrent_Client::loop();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">callback</span><span class="params">($ret, $callinfo)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">echo</span> $callinfo[<span class="string">'method'</span>] , <span class="string">" result: "</span>, $ret , <span class="string">"\n"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/* 注册一个异步调用 */</span></span><br><span class="line">Yar_Concurrent_Client::call(<span class="string">"http://example.com/operator.php"</span>, <span class="string">"add"</span>, <span class="keyword">array</span>(<span class="number">1</span>, <span class="number">2</span>), <span class="string">"callback"</span>);</span><br><span class="line"><span class="comment">/* 发送所有注册的调用, 等待返回, 返回后Yar会调用callback回掉函数 */</span></span><br><span class="line">Yar_Concurrent_Client::loop();</span><br><span class="line"><span class="comment">/* 重置call ,否则上面的call会调用*/</span></span><br><span class="line">Yar_Concurrent_Client::reset();</span><br><span class="line">Yar_Concurrent_Client::call(<span class="string">"http://example.com/operator.php"</span>, <span class="string">"sub"</span>, <span class="keyword">array</span>(<span class="number">2</span>, <span class="number">1</span>), <span class="string">"callback"</span>);</span><br><span class="line">Yar_Concurrent_Client::loop();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="Yaf官方文档"><a href="#Yaf官方文档" class="headerlink" title="Yaf官方文档"></a>Yaf官方文档</h1><p><a href="https://www.php.net/manual/zh/book.yaf.php" target="_blank" rel="noopener">php net yaf官网</a><br><a href="https://www.laruence.com/manual/index.html" target="_blank" rel="noopener">中文文档</a></p>
<h3 id="Yaf的优点"><a href="#Yaf的优点" class="headerlink" title="Yaf的优点"></a>Yaf的优点</h3><ul>
<li>用C语言开发的PHP框架, 相比原生的PHP, 几乎不会带来额外的性能开销.</li>
<li>所有的框架类, 不需要编译, 在PHP启动的时候加载, 并常驻内存.</li>
<li>更短的内存周转周期, 提高内存利用率, 降低内存占用率.</li>
<li>灵巧的自动加载. 支持全局和局部两种加载规则, 方便类库共享.</li>
<li>高性能的视图引擎.</li>
<li>高度灵活可扩展的框架, 支持自定义视图引擎, 支持插件, 支持自定义路由等等.</li>
<li>内建多种路由, 可以兼容目前常见的各种路由协议.</li>
<li>强大而又高度灵活的配置文件支持. 并支持缓存配置文件, 避免复杂的配置结构带来的性能损失.</li>
<li>在框架本身,对危险的操作习惯做了禁止.</li>
<li>更快的执行速度, 更少的内存占用.</li>
</ul>
<h2 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">Yaf can be installed from source code by:</span><br><span class="line"></span><br><span class="line">cd /path/to/yaf-src/</span><br><span class="line">phpize</span><br><span class="line">./configure</span><br><span class="line">make</span><br><span class="line">sudo make install</span><br></pre></td></tr></table></figure>
<h2 id="路由改写，伪静态"><a href="#路由改写，伪静态" class="headerlink" title="路由改写，伪静态"></a>路由改写，伪静态</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">http:<span class="comment">//dev-all.ekeguan.com/test/1/1.html</span></span><br><span class="line"></span><br><span class="line">在 Bootstrap.php 中 _initRoute 增加：</span><br><span class="line"><span class="comment">//http://dev-all.ekeguan.com/product/list/1/2</span></span><br><span class="line"> $router = $dispatcher-&gt;getRouter();</span><br><span class="line">$route  = <span class="keyword">new</span> Yaf_Route_Rewrite(</span><br><span class="line">        <span class="string">"/product/list/:id/:name"</span>,</span><br><span class="line">        <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">"controller"</span> =&gt; <span class="string">"index"</span>,</span><br><span class="line">            <span class="string">"action"</span>     =&gt; <span class="string">"index"</span>,</span><br><span class="line">        )</span><br><span class="line">    ); </span><br><span class="line">    </span><br><span class="line">    $router-&gt;addRoute(<span class="string">'dummy'</span>, $route);</span><br><span class="line"><span class="comment">// http://dev-all.ekeguan.com/user-list/1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// http://dev-all.ekeguan.com/test/1/1.html</span></span><br><span class="line"></span><br><span class="line">    $config = <span class="keyword">array</span>(</span><br><span class="line">     <span class="string">"user-list"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">        <span class="string">"type"</span>  =&gt; <span class="string">"rewrite"</span>,        <span class="comment">//Yaf_Route_Rewrite route</span></span><br><span class="line">        <span class="string">"match"</span> =&gt; <span class="string">"/user-list/:id"</span>, <span class="comment">//match only /user/list/?/</span></span><br><span class="line">        <span class="string">"route"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">'controller'</span> =&gt; <span class="string">"index"</span>,  <span class="comment">//route to user controller,</span></span><br><span class="line">            <span class="string">'action'</span>     =&gt; <span class="string">"index"</span>,  <span class="comment">//route to list action</span></span><br><span class="line">        ),</span><br><span class="line">     ),</span><br><span class="line">     <span class="string">"test"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">        <span class="string">"type"</span>  =&gt; <span class="string">"regex"</span>,          <span class="comment">//Yaf_Route_Regex route</span></span><br><span class="line">        <span class="string">"match"</span> =&gt; <span class="string">"#^/test/([^/]+)/([^/])(.*)\.html+#"</span>,         <span class="comment">//match arbitrary request uri</span></span><br><span class="line">        <span class="string">"route"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">            <span class="string">'controller'</span> =&gt; <span class="string">"index"</span>,  <span class="comment">//route to product controller,</span></span><br><span class="line">            <span class="string">'action'</span>     =&gt; <span class="string">"index"</span>,    <span class="comment">//route to dummy action</span></span><br><span class="line">        ),</span><br><span class="line">        <span class="string">"map"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">           <span class="number">1</span> =&gt; <span class="string">"uri"</span>,   <span class="comment">// now you can call $request-&gt;getParam("uri")</span></span><br><span class="line">        ),</span><br><span class="line">     ),</span><br><span class="line"> );</span><br><span class="line"></span><br><span class="line"> $router-&gt;addConfig(<span class="keyword">new</span> Yaf_Config_Simple($config));</span><br><span class="line"> </span><br><span class="line"> </span><br><span class="line"> <span class="comment">//分页</span></span><br><span class="line"> $router = $dispatcher-&gt;getRouter();</span><br><span class="line">$config = <span class="keyword">array</span>(</span><br><span class="line">   <span class="string">"detail"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">      <span class="string">"type"</span>  =&gt; <span class="string">"regex"</span>,          <span class="comment">//Yaf_Route_Regex route</span></span><br><span class="line">      <span class="string">"match"</span> =&gt; <span class="string">"#^/details/(\d+)\/?(\d?)(\.html)?#"</span>,         <span class="comment">//match arbitrary request uri</span></span><br><span class="line">      <span class="string">"route"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">          <span class="string">'controller'</span> =&gt; <span class="string">"index"</span>,  <span class="comment">//route to product controller,</span></span><br><span class="line">          <span class="string">'action'</span>     =&gt; <span class="string">"index"</span>,    <span class="comment">//route to dummy action</span></span><br><span class="line">      ),</span><br><span class="line">      <span class="string">"map"</span> =&gt; <span class="keyword">array</span>(</span><br><span class="line">         <span class="number">1</span> =&gt; <span class="string">"id"</span>,   <span class="comment">// now you can call $request-&gt;getParam("uri")</span></span><br><span class="line">         <span class="number">2</span> =&gt; <span class="string">"page"</span>,   <span class="comment">// now you can call $request-&gt;getParam("uri")</span></span><br><span class="line">      ),</span><br><span class="line">   ),</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line">$router-&gt;addConfig(<span class="keyword">new</span> Yaf_Config_Simple($config));</span><br></pre></td></tr></table></figure>
<h2 id="CLI模式"><a href="#CLI模式" class="headerlink" title="CLI模式"></a>CLI模式</h2><h3 id="第一种方式"><a href="#第一种方式" class="headerlink" title="第一种方式"></a>第一种方式</h3><p>在<code>public</code>目录下新建<code>cli.php</code>文件</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">if</span>(php_sapi_name()!=<span class="string">'cli'</span>)&#123;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">'No authority'</span>;<span class="keyword">exit</span>();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$application = <span class="keyword">new</span> Yaf_Application(GLOBAL_CONFIG_PATH.<span class="string">'application.ini'</span>);</span><br><span class="line">$application-&gt;execute(<span class="string">"main1"</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">main1</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">"hello\n"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>运行 <code>php cli.php</code> 直接执行，运行函数</p>
<h3 id="第二种方式"><a href="#第二种方式" class="headerlink" title="第二种方式"></a>第二种方式</h3><p>在<code>public</code>目录下新建<code>cli.php</code>文件</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> * cli命令行</span></span><br><span class="line"><span class="comment"> * 此文件不允许http方式访问</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">if</span> (php_sapi_name() != <span class="string">'cli'</span>) &#123;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">'No authority'</span>;<span class="keyword">exit</span>();</span><br><span class="line">&#125;</span><br><span class="line">define(<span class="string">'ENVIRONMENT'</span>, <span class="string">'develop'</span>); <span class="comment">//生成环境请修改为product</span></span><br><span class="line">define(<span class="string">'ROOT_PATH'</span>, dirname(<span class="keyword">__FILE__</span>));</span><br><span class="line">define(<span class="string">'APP_PATH'</span>, realpath(ROOT_PATH . <span class="string">'/../'</span>)); <span class="comment">//指向上一级</span></span><br><span class="line"></span><br><span class="line">define(<span class="string">'GLOBAL_CONFIG_PATH'</span>, <span class="string">'/home/www/config/'</span>);</span><br><span class="line">defined(<span class="string">'REFERER'</span>) ? REFERER : define(<span class="string">'REFERER'</span>, <span class="keyword">isset</span>($_SERVER[<span class="string">'HTTP_REFERER'</span>]) ? $_SERVER[<span class="string">'HTTP_REFERER'</span>] : <span class="string">'/'</span>); <span class="comment">//上一页</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">switch</span> (ENVIRONMENT) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'develop'</span>:</span><br><span class="line">        error_reporting(E_ALL &amp; ~E_NOTICE); <span class="comment">//报告所有的错误，但除了E_NOTICE这一种</span></span><br><span class="line">        ini_set(<span class="string">'display_errors'</span>, <span class="number">1</span>);</span><br><span class="line">        ini_set(<span class="string">'yaf.environ'</span>, <span class="string">'develop'</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">'product'</span>:</span><br><span class="line">        ini_set(<span class="string">'display_errors'</span>, <span class="number">0</span>);</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">    <span class="keyword">default</span>:</span><br><span class="line">        header(<span class="string">'HTTP/1.1 503 Service Unavailable.'</span>, <span class="keyword">true</span>, <span class="number">503</span>);</span><br><span class="line">        <span class="keyword">echo</span> <span class="string">'The application environment is not set correctly.'</span>;</span><br><span class="line">        <span class="keyword">exit</span>(<span class="number">1</span>); <span class="comment">// EXIT_ERROR</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$application = <span class="keyword">new</span> Yaf_Application(GLOBAL_CONFIG_PATH . <span class="string">'application.ini'</span>);</span><br><span class="line"><span class="comment">//加载cli的bootstrap配置内容</span></span><br><span class="line">$application-&gt;bootstrap();</span><br><span class="line"></span><br><span class="line"><span class="comment">//获取argv参数</span></span><br><span class="line">$uri_r = explode(<span class="string">'/'</span>, $argv[<span class="number">1</span>]);</span><br><span class="line">$count = count($uri_r);</span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> ($count &gt; <span class="number">3</span> &amp;&amp; $count &lt;= <span class="number">1</span>) &#123;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">'uri error!'</span>;</span><br><span class="line">    <span class="keyword">exit</span>;</span><br><span class="line">&#125; <span class="keyword">elseif</span> ($count == <span class="number">2</span>) &#123;</span><br><span class="line">    <span class="comment">// 默认模块为空</span></span><br><span class="line">    array_unshift($uri_r, <span class="string">''</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">list</span>($module, $controller, $action) = $uri_r;</span><br><span class="line"></span><br><span class="line">$params = [];</span><br><span class="line"><span class="keyword">if</span> (<span class="keyword">isset</span>($argv[<span class="number">2</span>]) &amp;&amp; !<span class="keyword">empty</span>($argv[<span class="number">2</span>])) &#123;</span><br><span class="line">    parse_str($argv[<span class="number">2</span>], $params);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">$request = <span class="keyword">new</span> Yaf_Request_Simple(<span class="string">'CLI'</span>, $module, $controller, $action, $params);</span><br><span class="line">$application-&gt;getDispatcher()-&gt;returnResponse(<span class="keyword">true</span>)-&gt;dispatch($request);</span><br></pre></td></tr></table></figure>
<p>使用方法运行<code>php cli2.php  account/account/login &quot;name=Bill&amp;age=60&quot;</code>,分别为模块，控制器，方法  参数一定加上引号 , 其中参数在 <code>controller</code> 中 使用 <code>$this-&gt;getRequest()-&gt;getParams()</code> 控制器里使用这个方法接受参数。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>分享即是成长</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat-reward-image.png" alt="changyuan 微信支付">
        <p>微信支付</p>
      </div>
    

    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    changyuan
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://changyuan.github.io/2020/05/10/yaf/" title="Yaf Yar使用">http://changyuan.github.io/2020/05/10/yaf/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/yaf/" rel="tag"># yaf</a>
          
            <a href="/tags/rewrite/" rel="tag"># rewrite</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/05/02/go-concurrency/" rel="next" title="Go 并发">
                <i class="fa fa-chevron-left"></i> Go 并发
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2021/09/27/go-dockerfile/" rel="prev" title="golang项目部署(Dockerfile)">
                golang项目部署(Dockerfile) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="changyuan">
            
              <p class="site-author-name" itemprop="name">changyuan</p>
              <p class="site-description motion-element" itemprop="description">不断升级自己的操作系统</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">69</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">26</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/changyuan" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-fab fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://twitter.com/changocean1" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-fab fa-twitter"></i>Twitter</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="http://weibo.com/changyuan2011" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-fab fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.douban.com/people/changyuanyuan" target="_blank" title="Zhihu">
                      
                        <i class="fa fa-fw fa-fab fa-quora"></i>Zhihu</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://weibo.com/changyuan2011" title="Weibo" target="_blank">Weibo</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://github.com/changyuan" title="GitHub" target="_blank">GitHub</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Yar-Yet-Another-RPC-Framework-一个rpc框架"><span class="nav-number">1.</span> <span class="nav-text">Yar (Yet Another RPC Framework) 一个rpc框架</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#范例"><span class="nav-number">1.0.1.</span> <span class="nav-text">范例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多个客户端异步调用"><span class="nav-number">1.1.</span> <span class="nav-text">多个客户端异步调用</span></a></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#Yaf官方文档"><span class="nav-number">2.</span> <span class="nav-text">Yaf官方文档</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Yaf的优点"><span class="nav-number">2.0.1.</span> <span class="nav-text">Yaf的优点</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#安装"><span class="nav-number">2.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#路由改写，伪静态"><span class="nav-number">2.2.</span> <span class="nav-text">路由改写，伪静态</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#CLI模式"><span class="nav-number">2.3.</span> <span class="nav-text">CLI模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#第一种方式"><span class="nav-number">2.3.1.</span> <span class="nav-text">第一种方式</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#第二种方式"><span class="nav-number">2.3.2.</span> <span class="nav-text">第二种方式</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">changyuan</span>

  
</div>









<!-- 网站运行时间的设置 -->
<span id="timeDate">载入天数...</span>
<span id="times">载入时分秒...</span>
<script>
    var now = new Date();
    function createtime() {
        var grt= new Date("08/08/2014 00:00:00");
        now.setTime(now.getTime()+250);
        days = (now - grt ) / 1000 / 60 / 60 / 24; dnum = Math.floor(days);
        hours = (now - grt ) / 1000 / 60 / 60 - (24 * dnum); hnum = Math.floor(hours);
        if(String(hnum).length ==1 ){hnum = "0" + hnum;} minutes = (now - grt ) / 1000 /60 - (24 * 60 * dnum) - (60 * hnum);
        mnum = Math.floor(minutes); if(String(mnum).length ==1 ){mnum = "0" + mnum;}
        seconds = (now - grt ) / 1000 - (24 * 60 * 60 * dnum) - (60 * 60 * hnum) - (60 * mnum);
        snum = Math.round(seconds); if(String(snum).length ==1 ){snum = "0" + snum;}
        document.getElementById("timeDate").innerHTML = "本站已运行 "+dnum+" 天 ";
        document.getElementById("times").innerHTML = hnum + " 小时 " + mnum + " 分 " + snum + " 秒.";
    }
setInterval("createtime()",250);
</script>

        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
